import java.util.Arrays;
import java.util.Comparator;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;
    private static final int DEFAULT_SIZE = 10;
 
    public PriorityQueue(int k, Comparator<Integer> comparator) {
        this.elem = new int[DEFAULT_SIZE];
    }
 
    /**
     * 建堆的时间复杂度：O(N)
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            if(isFull()) {
                elem = Arrays.copyOf(elem,elem.length + elem.length>>>1);
            }
            this.elem[i] = array[i];
            usedSize++;
        }
        //调整每个根节点
        for (int i = (usedSize - 1 - 1) / 2; i >= 0; i--) {
            shiftDown(i,usedSize);
        }
    }
 
    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root * 2 + 1;
        while(child < len) {
            if (child + 1 < len && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[root] < elem[child]) {
                int tmp = elem[child];
                elem[child] = elem[root];
                elem[root] = tmp;
                root = child;
                child = root * 2 + 1;
            } else {
                break;
            }
        }
    }
 
 
    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length + elem.length>>>1);
        }
        this.elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize - 1);
    }
 
    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(parent >= 0) {
            if(this.elem[parent] < this.elem[child]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }
    }
 
    public boolean isFull() {
        return usedSize == this.elem.length;
    }
 
    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public int pollHeap() {
        if(isEmpty()) {
            throw(new NullPointerException());
        }
        int tmp = this.elem[usedSize];
        this.elem[usedSize] = this.elem[0];
        this.elem[0] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
        return this.elem[usedSize];
    }
 
    public boolean isEmpty() {
        return this.usedSize == 0;
    }
 
    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(isEmpty()) {
            throw(new NullPointerException());
        }
        return this.elem[0];
    }
}